package cn.quevo.spring.convert;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import cn.quevo.core.enums.TypeConvertEnum;
import cn.quevo.core.exception.TypeConvertException;
import cn.quevo.core.lang.DateFormatUtils;
import cn.quevo.core.lang.StringUtils;

/**
 * 日期类型转换器
 * 
 * @author July july_sky@foxmail.com
 * @date 2018年3月30日 上午11:30:30
 * @Copyright ©2015-2035 湘豫(北京)科技有限公司. All Rights Reserved.
 * @version 1.0
 */
public class CustomDateEditor extends PropertyEditorSupport {

    private DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (StringUtils.isBlank(text)) {
            super.setValue(null);
            return;
        }
        String[] args = DateFormatUtils.getDateConvert(text);
        if (args == null) {
            try {
                throw new TypeConvertException(TypeConvertEnum.DATE);
            } catch (TypeConvertException e) {
                throw new IllegalArgumentException("日期格式错误", e);
            }
        }
        this.dateFormat = new SimpleDateFormat(args[1]);
        try {
            super.setValue(dateFormat.parse(args[0]));
        } catch (ParseException e) {
            throw new IllegalArgumentException("日期转换异常", e);
        }
    }

    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        return (value != null ? this.dateFormat.format(value) : "");
    }
}
